﻿/*
    Copyright (c) 2011, Jeremy Randall (http://www.auburnrandall.com)
      
    All rights reserved.
 
    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
 
    1. Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.
 
    2. Redistributions in binary form must reproduce the above copyright 
    notice, this list of conditions and the following disclaimer in 
    the documentation and/or other materials provided with the distribution.
 
    3. The names of the authors may not be used to endorse or promote products
    derived from this software without specific prior written permission.
 
    THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES,
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
    FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
    OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
    OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
    EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace FormEngine.Web
{
    public class FormControl : WebControl, INamingContainer 
    {
        private List<InputControl> _inputControls = new List<InputControl>();
        private List<Control> _bindables = new List<Control>();

        [PersistenceMode(PersistenceMode.InnerProperty)]
        public Style LabelStyle { get; set; }

        public FormParser FormParser
        {
            get { return ViewState["FormParser"] as FormParser; }
            set { ViewState["FormParser"] = value; }
        }

        /// <summary>
        /// Updates the input fields with submitted data.
        /// </summary>
        public void UpdateFields()
        {
            EnsureChildControls();

            foreach (InputControl ic in _inputControls)
            {
                switch (ic.FieldDetail.FieldType)
                {
                    case FieldType.Text:
                        TextBox tb = (TextBox)ic.Control;
                        ic.FieldDetail.FieldValue = tb.Text;

                        break;

                    case FieldType.CheckBox:
                        CheckBox cb = (CheckBox)ic.Control;
                        if (cb.Checked)
                        {
                            ic.FieldDetail.FieldValue = "On"; // TODO: PDF specific syntax
                        }

                        break;

                    case FieldType.RadioButton:
                        RadioButtonList rbl = (RadioButtonList)ic.Control;
                        ic.FieldDetail.FieldValue = rbl.SelectedValue;

                        break;
                }
            }
        }

        protected override void CreateChildControls()
        {
            _bindables.Clear();
            _inputControls.Clear();

            foreach (FieldDetail field in FormParser.Fields)
            {
                Control ctrl = null;

                switch (field.FieldType)
                {
                    case FieldType.Text:
                        ctrl = CreateTextBox(field);
                        break;

                    case FieldType.CheckBox:
                        ctrl = CreateCheckBox(field);
                        break;

                    case FieldType.RadioButton:
                        ctrl = CreateRadioButtonList(field);
                        break;
                }

                if (ctrl != null)
                {
                    InputControl ic = new InputControl() { Control = ctrl, FieldDetail = field };
                    _inputControls.Add(ic);

                    this.Controls.Add(ctrl);
                }
            }

            foreach (Control c in _bindables)
            {
                c.DataBind();
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            writer.RenderBeginTag(HtmlTextWriterTag.Table);

            foreach (InputControl ic in _inputControls)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Tr);

                if (LabelStyle != null)
                {
                    writer.EnterStyle(LabelStyle, HtmlTextWriterTag.Td);
                }
                else
                {
                    writer.AddAttribute(HtmlTextWriterAttribute.Class, "formlabel");
                    writer.RenderBeginTag(HtmlTextWriterTag.Td);
                }

                writer.Write(ic.FieldDetail.Name);

                if (LabelStyle != null)
                {
                    writer.ExitStyle(LabelStyle, HtmlTextWriterTag.Td);
                }
                else
                {
                    writer.RenderEndTag(); // td
                }

                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                ic.Control.RenderControl(writer);
                writer.RenderEndTag();

                writer.RenderEndTag(); // tr
            }

            writer.RenderEndTag(); // table
        }

        private TextBox CreateTextBox(FieldDetail field)
        {
            TextBox tb = new TextBox();

            if (!Page.IsPostBack)
            {
                tb.Text = field.FieldValue;
            }

            return tb;
        }

        private CheckBox CreateCheckBox(FieldDetail field)
        {
            CheckBox cb = new CheckBox();

            return cb;
        }

        private RadioButtonList CreateRadioButtonList(FieldDetail field)
        {
            RadioButtonList rbl = new RadioButtonList();
            rbl.DataSource = field.Options;
            rbl.DataTextField = "Name";

            _bindables.Add(rbl);

            return rbl;
        }

        private class InputControl
        {
            public Control Control { get; set; }
            public FieldDetail FieldDetail { get; set; }
        }
    }
}
